//
//  LeverCollectionView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/5/7.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
protocol leverDelegate: class {
    func upHeight(openBool:Bool)
    func updateTradePrice()
}
enum leverStyle {
    case commonStyle
    case limiteStyle
}
class LeverCollectionView: UIView {
    var openSelect:Bool = false //是否打开止盈止损
    var viewModel:LeverSheetViewModel?
    weak var delegate:leverDelegate?
    var config:LeverConfig?
    var model:LeverCapitalModel?
    var dataSource:SelectmangerDelegate?
    var collectionView:UICollectionView?
    var selectStyle:leverStyle? //标记是市价 还是 限价
    
    var leverModel:LeverDataModel = LeverDataModel()

    
    var priceTextField:BaseTextField? //限价
    var numberTextField:BaseTextField? //交易个数
    var stopLossTextField:BaseTextField? //止损
    var stopProfitTextField:BaseTextField? //止盈
    var buyBtn:UIButton?
    var sellBtn:UIButton?
    
    lazy var switBtn:UISwitch = {
         let switchBtn =  UISwitch()
         switchBtn.onTintColor = kGreenColor
         switchBtn.addTarget(self, action: #selector(switBtnAction), for: UIControlEvents.touchUpInside)
        return switchBtn
    }()
    lazy var bzjLable:BaseLabel = {
        let label = BaseLabel(style: .twiceStyle)
        label.font = UIFont.systemFont(ofSize: 11)
        label.text = ""
        return label
    }()
    
    lazy var chargeLabel:BaseLabel = {
        let chargeLabel = BaseLabel(style: .twiceStyle)
        chargeLabel.text = kText("手续费")
        chargeLabel.font = UIFont.systemFont(ofSize: 12)
        return chargeLabel
    }()
    
    lazy var moneyLabel: BaseLabel = {
        let moneyLabel = BaseLabel(style: .twiceStyle)
        moneyLabel.textAlignment = NSTextAlignment.right
        moneyLabel.font = UIFont.systemFont(ofSize: 12)
        return moneyLabel
    }()
    lazy var nameLabel: BaseLabel = {
        let nameLabel = BaseLabel(style: .twiceStyle)
        nameLabel.text = kText("止盈止损设置")
        nameLabel.font = UIFont.systemFont(ofSize: 12)
        return nameLabel
    }()
    
    lazy var inforLabel: BaseLabel = {
        let inforLabel = BaseLabel(style: .twiceStyle)
        inforLabel.text = kText("注：止盈止损设置，指的是盈亏达到保证金的比率")
        inforLabel.textAlignment = NSTextAlignment.center
        inforLabel.font = UIFont.systemFont(ofSize: 12)
        return inforLabel
    }()
    
    lazy var stopLossLabel: BaseLabel = {
        let label = BaseLabel(style: .twiceStyle)
        label.text = kText("注：止盈止损设置，指的是盈亏达到保证金的比率")
        label.textAlignment = NSTextAlignment.center
        label.font = UIFont.systemFont(ofSize: 12)
        return label
    }()
    
    init(config:SelectConfig ,model:SheetModel ,dataSource:SelectmangerDelegate,style:leverStyle) {
        super.init(frame: CGRect.zero)
        self.config = config as? LeverConfig
        self.model = model as? LeverCapitalModel
        selectStyle = style
        self.setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpUI() -> Void {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumInteritemSpacing = 5
        layout.minimumLineSpacing = 10
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0,  0)
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        self.collectionView = collectionView
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.clear
        collectionView.register(LeverCommonCell.self, forCellWithReuseIdentifier: "identifier")
        collectionView.register(LeverCommonCell.self, forCellWithReuseIdentifier: "identifier1")
        collectionView.register(LeverCommonCell.self, forCellWithReuseIdentifier: "identifier2")
        collectionView.register(LeverCommonCell.self, forCellWithReuseIdentifier: "identifier3")
        collectionView.register(LeverCommonCell.self, forCellWithReuseIdentifier: "identifier4")
        collectionView.register(LeverCommonCell.self, forCellWithReuseIdentifier: "identifier5")
        collectionView.register(LeverCollectionViewCell.self, forCellWithReuseIdentifier: "leverIdentifier")
        self.addSubview(collectionView)
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "collettionSectionFooter")
        collectionView.snp.makeConstraints { (make) in
            make.top.bottom.right.left.equalToSuperview()
        }
    }

    @objc func switBtnAction() {
        openSelect = !openSelect
        if openSelect {
            collectionView?.reloadData()
        }else {
            collectionView?.reloadData()
        }
        collectionView?.reloadData()
        if delegate != nil {
            self.delegate?.upHeight(openBool: openSelect)
        }
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}

extension LeverCollectionView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        if selectStyle == leverStyle.limiteStyle {
            return model!.gavelockLimtArr.count
            
        }
        if !openSelect  {
            return 5
        }
        return (model?.gavelockSheetArr.count)!
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if selectStyle == leverStyle.limiteStyle {
            return (model?.gavelockLimtArr[section].count)!
        }else {
            return (model?.gavelockSheetArr[section].count)!
        }
    }
    
 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let smallModel:LeverSheetModel?
    if selectStyle == leverStyle.limiteStyle {
        smallModel = model?.gavelockLimtArr[indexPath.section][indexPath.row]
    }else{
        smallModel = model?.gavelockSheetArr[indexPath.section][indexPath.row]
    }
    if smallModel?.style == .leverTitleStyle {
        let cell:LeverCommonCell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier", for: indexPath)
            as! LeverCommonCell
        cell.titleLabel.isHidden = false
        cell.titleLabel.text = smallModel?.name
        if (leverModel.isEqual(viewModel?.markModel)) {
        if indexPath.section == 1 && leverModel.isBuyBool && (viewModel?.isMarketBool)!{
            cell.titleLabel.text = kText("交易额")
        }
       }
        return cell
    }else if smallModel?.style == .leverBuyStyle {
        let cell:LeverCommonCell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier1", for: indexPath)
            as! LeverCommonCell
        cell.priceBtn.isHidden = false
        cell.changePriceBtn(index:indexPath.row,isSelected:leverModel.isBuyBool)
        cell.priceBtn.addTarget(self, action: #selector(priceBtnAction(sender:)), for: UIControlEvents.touchUpInside)
        if indexPath.row == 1 {
            buyBtn  = cell.priceBtn
        }else {
            sellBtn = cell.priceBtn
        }
        if selectStyle == .commonStyle {
            if indexPath.row == 1 {
                cell.priceBtn.setTitle(String(format: "%@ %@",kText("买入"),CYCalculate.cy_intercept(number: self.leverModel.buyPrice, digit: 6)!), for: UIControlState.normal)
            }else {
                cell.priceBtn.setTitle(String(format: "%@ %@",kText("卖出"),CYCalculate.cy_intercept(number: self.leverModel.sellPrice, digit: 6)!), for: UIControlState.normal)
            }
            
        }else {
            cell.priceBtn.setTitle(smallModel?.name, for: UIControlState.normal)
        }
        return cell
    }else if smallModel?.style == .leverTradeStyle {
        let cell:LeverCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "leverIdentifier", for: indexPath) as! LeverCollectionViewCell
        cell.writextField.changeView = self.superview
        cell.index = indexPath.section
        cell.delegate = self
        if selectStyle == .commonStyle {
            if indexPath.section == 1 {
                numberTextField = cell.writextField
                numberTextField?.text = self.leverModel.number
            }else if indexPath.section == 5 {
                stopLossTextField = cell.writextField
                stopLossTextField?.text = self.leverModel.stopLoss
            }else if indexPath.section == 6 {
                stopProfitTextField = cell.writextField
                stopProfitTextField?.text = self.leverModel.stopProfit
            }
        }else {
            if indexPath.section == 1 {
                priceTextField = cell.writextField
                priceTextField?.text = self.leverModel.price
            }else if indexPath.section == 2 {
                numberTextField = cell.writextField
                numberTextField?.text = self.leverModel.number
            }else if indexPath.section == 5 {
                stopLossTextField = cell.writextField
                stopLossTextField?.text = self.leverModel.stopLoss
            }else if indexPath.section == 6 {
                stopProfitTextField = cell.writextField
                stopProfitTextField?.text = self.leverModel.stopProfit
            }
        }
        cell.writextField.delegate = self
        cell.writextField.addTarget(self, action: #selector(textFieldDidChangeValue(textField:)), for:UIControlEvents.editingChanged)
        
        return cell
    }else if smallModel?.style == .leverSwitchStyle {
        let cell:LeverCommonCell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier2", for: indexPath) as! LeverCommonCell
        switBtn.isOn = openSelect
        cell.contentView.addSubview(switBtn)
        switBtn.snp.remakeConstraints { (make) in
            make.right.equalToSuperview().offset(15)
            make.centerY.equalToSuperview()
            make.width.equalTo(60)
            make.height.equalTo(20)
        }
        switBtn.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
        return cell
    }else if smallModel?.style == .leverInforStyle {
        let cell:LeverCommonCell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier3", for: indexPath) as! LeverCommonCell
        moneyLabel.text = self.leverModel.bailInfo
        cell.contentView.addSubview(moneyLabel)
        moneyLabel.snp.remakeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview()
            make.left.equalToSuperview()
        }
        return cell
    }else if smallModel?.style == .leverPercentStyle {
        let cell:LeverCommonCell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier5", for: indexPath) as! LeverCommonCell
        cell.nameLabel.isHidden = false
        cell.nameLabel.text = "10"
        cell.kindLabel.isHidden = false
        cell.arrowDown.isHidden = false
        cell.nameLabel.snp.updateConstraints { (make) in
            make.right.equalToSuperview().offset(-20)
        }
        if indexPath.section == 5 {
            cell.nameLabel.text = leverModel.lossScales
        }else {
            cell.nameLabel.text = leverModel.profitScales
        }
        return cell
    }else {
        let cell:LeverCommonCell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier4", for: indexPath) as! LeverCommonCell
        cell.nameLabel.isHidden = false
    
        if self.leverModel.bail.count > indexPath.row - 1{
        cell.nameLabel.text = self.leverModel.bail[indexPath.row - 1]
        cell.isHidden = false
        }else {
           cell.isHidden = true
           cell.nameLabel.text = "0"
        }
        if self.leverModel.selectIndex + 1 == indexPath.row {
            cell.selectImage.isHidden = false
            cell.nameLabel.layer.borderColor = kThemeColor.cgColor
        }else {
            cell.nameLabel.layer.borderColor = KTableLineColor.cgColor
            cell.selectImage.isHidden = true
        }
        return cell
    }

 }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let smallModel:LeverSheetModel?
        if selectStyle == leverStyle.limiteStyle {
            smallModel = model?.gavelockLimtArr[indexPath.section][indexPath.row]
        }else{
            smallModel = model?.gavelockSheetArr[indexPath.section][indexPath.row]
        }
        if smallModel?.style == .leverTitleStyle {
           return CGSize(width: 103, height: 40)
        }else if smallModel?.style == .leverBuyStyle {
            return CGSize(width: (kSCREEN_WIDTH - 133)/2, height: 30)
        }else if smallModel?.style == .leverTradeStyle {
            return CGSize(width: kSCREEN_WIDTH - 128, height: 40)
        }else if smallModel?.style == .leverSwitchStyle {
           return CGSize(width: kSCREEN_WIDTH - 128, height: 40)
        }else if smallModel?.style == .leverInforStyle {
            return CGSize(width: kSCREEN_WIDTH - 128, height: 40)
        }else if indexPath.section == 5 || indexPath.section == 6 {
            return CGSize(width: kSCREEN_WIDTH - 128, height: 40)
        }else {
            return CGSize(width: (kSCREEN_WIDTH - 133)/4, height: 25)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        if section != 0 {
            return 10
        }
        return 0.1
    }
    
    
    //    minimumInteritemSpacingForSectionAtInde
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 5
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        if selectStyle == leverStyle.limiteStyle {
            if section == 3{
                return CGSize(width: kSCREEN_WIDTH, height: 5)
            }
            if section == 5 {
                return CGSize(width: kSCREEN_WIDTH, height: 15)
            }
            if section == 6 {
                return CGSize(width: kSCREEN_WIDTH, height: 15)
            }
        }else {
            
            if section == 2 || section == 3{
                return CGSize(width: kSCREEN_WIDTH, height: 10)
            }
            if section == 5 {
                return CGSize(width: kSCREEN_WIDTH, height: 15)
            }
            if section == 6 {
                return CGSize(width: kSCREEN_WIDTH, height: 15)
            }
        }
        
        return CGSize.zero
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "collettionSectionFooter", for: indexPath)
        view.backgroundColor = UIColor.clear
        if selectStyle == leverStyle.limiteStyle {
            if indexPath.section == 3 {
                view.addSubview(bzjLable)
                let tradeNumber = viewModel?.archiveDigitNumber(model: leverModel, isNumber: false, isLimitPrice:false)
                bzjLable.text = String(format: "%@ %@ %@",kText("可用保证金"),CYCalculate.cy_intercept(number: (viewModel?.tradeInfoModel.coinAssetModel.currentAmount)!, digit: tradeNumber!, isCover: false)!,(viewModel?.archivePairName(model: leverModel))!)
                bzjLable.snp.makeConstraints { (make) in
                    make.top.equalToSuperview().offset(3)
                    make.right.equalToSuperview().offset(-15)
                }
            }
            return view
        }
        
        if indexPath.section == 2 {
            if !openSelect {
               inforLabel.isHidden = true
            }
            view.addSubview(bzjLable)
            let tradeNumber = viewModel?.archiveDigitNumber(model: leverModel, isNumber: false, isLimitPrice:false)
            bzjLable.text = String(format: "%@ %@ %@",kText("可用保证金"),CYCalculate.cy_intercept(number: leverModel.coinAsset, digit: tradeNumber!, isCover: false)!,(viewModel?.archivePairName(model: leverModel))!)
            bzjLable.snp.remakeConstraints { (make) in
                make.top.equalToSuperview().offset(3)
                make.right.equalToSuperview().offset(-15)
            }
        }
        if indexPath.section == 3 {
            view.themeBackground = ThemeManager.ThemeColorKeys.background3
        }
        return view
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        if selectStyle == leverStyle.limiteStyle {
            if section == 0 {
                return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            }else if section == 5{
                return UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0)
            }else {
                return UIEdgeInsets(top: 15, left: 0, bottom: 0, right: 0)
            }
        }
        
        if section == 0 || section == 3 || section == 4{
            return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        }else if section == 1 || section == 2 {
            return UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
        }else {
            return UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.section == 5 || indexPath.section == 6 {
            let name = indexPath.section == 5 ? kText("触发止损") : kText("触发止盈")
            let selectStr = indexPath.section == 5 ? leverModel.lossScales : leverModel.profitScales
            let selectPickerView = SlecterManager.manager.creatSlecterStyle(style: .identiStyle, title: name, selectStr: selectStr as AnyObject, dataArr: KLevelScalesArr, dataSource: self)
            selectPickerView.tag = indexPath.section * 1000
            
            selectPickerView.pickerShow()
            return
        }
        
        if indexPath.row == 0 {
            return
        }
        if selectStyle == leverStyle.limiteStyle {
            self.changeSelectDail(row: indexPath.row)
        }else {
            self.changeSelectDail(row: indexPath.row)
        }
        
        self.updatePrice()
    }
    
    func changeSelectDail(row:Int)  {
        self.leverModel.selectIndex = row - 1
        self.viewModel?.changePrice = true
        collectionView?.reloadData()
    }
    
    func updatePrice() {
        if delegate != nil && delegate?.updateTradePrice != nil {
            self.delegate?.updateTradePrice()
        }
    }
}

extension LeverCollectionView {
    
    func setModel(viewModel:LeverSheetViewModel)  {
       self.viewModel = viewModel
        if selectStyle == .commonStyle {
            self.leverModel = viewModel.markModel
        }else {
            self.leverModel = viewModel.limitModel
        }
        switBtn.onTintColor = self.leverModel.isBuyBool ? kGreenColor : kRedColor
        self.viewModel?.changeLeverModelInformation(model: self.leverModel)
        collectionView?.reloadData()
        if selectStyle == .commonStyle {
            self.updatePrice()
        }
    }
    
    @objc func priceBtnAction(sender:UIButton) {
        if sender.isEqual(buyBtn) {
            leverModel.isBuyBool = true
            switBtn.onTintColor = kGreenColor
        }else {
            leverModel.isBuyBool = false
            switBtn.onTintColor = kRedColor
        }
        self.clear()
    }
    
    func clear()  {
        leverModel.selectIndex = 0
        leverModel.number = ""
        
        viewModel?.changeLeverModelInformation(model: self.leverModel)
        collectionView?.reloadData()
         self.updatePrice()
    }
}

extension LeverCollectionView: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {
        if string.count == 0 {
            return true
        }
        if textField.isEqual(priceTextField) {
            let number = self.viewModel?.archiveDigitNumber(model: leverModel, isNumber: false, isLimitPrice: true)
            return textField.cheakNumberFormat(digit: number!, range: range, string: string, interger: 6)
        }else if textField.isEqual(numberTextField){
            let number = self.viewModel?.archiveDigitNumber(model: leverModel, isNumber: true, isLimitPrice: false)
            return textField.cheakNumberFormat(digit: number!, range: range, string: string, interger: 6)
        }else {
            let number = self.viewModel?.archiveDigitNumber(model: leverModel, isNumber: false, isLimitPrice: false)
            return textField.cheakNumberFormat(digit: number!, range: range, string: string, interger: 6)
        }
    }
    @objc func textFieldDidChangeValue(textField:UITextField) {
        if textField.isEqual(priceTextField) {
            self.leverModel.price = (priceTextField?.text)!
            self.viewModel?.changePrice = true
            self.updatePrice()
            if !(viewModel?.isMarketBool)! {
                collectionView?.reloadSections([4])
            }else {
                collectionView?.reloadSections([3])
            }
            
        }else if textField.isEqual(numberTextField) {
            self.leverModel.number = (numberTextField?.text)!
            self.viewModel?.changePrice = true
            self.updatePrice()
            if !(viewModel?.isMarketBool)! {
                collectionView?.reloadSections([4])
            }else {
                collectionView?.reloadSections([3])
            }
            self.updatePrice()
        }else if textField.isEqual(stopLossTextField) {
            if textField.text?.count != 0 {
                let number = self.viewModel?.archiveDigitNumber(model: leverModel, isNumber: false, isLimitPrice: false)
                if CYCalculate.campare(firstNumber: Double(textField.text!)!, lastNumber: leverModel.limitloss) == .larget {
                    textField.text! = CYCalculate.cy_intercept(number: leverModel.limitloss, digit: number!)!
                }
            }
            
            self.leverModel.stopLoss = textField.text!
        }else if textField.isEqual(stopProfitTextField) {
            self.leverModel.stopProfit = textField.text!
        }
    }
    
}

extension LeverCollectionView: leverCellDelegate {
    
    func changeNumber(index: Int, addBool: Bool) {
        if selectStyle == .commonStyle {
            if index == 1 {
                numberTextField?.text = viewModel?.leverNumberChange(addBool: addBool)
                self.viewModel?.changePrice = true
                self.updatePrice()
                collectionView?.reloadData()
                self.updatePrice()
            }else if index == 5 {
                stopLossTextField?.text = viewModel?.leverLossChange(addBool: addBool)
            }else if index == 6 {
                stopProfitTextField?.text = viewModel?.leverProfitChange(addBool: addBool)
            }
            
        }else {
            if index == 1 {
                priceTextField?.text = viewModel?.leverPriceChange(addBool: addBool)
                self.viewModel?.changePrice = true
                viewModel?.archiLossInfor(model: leverModel)
                viewModel?.archiveProfitInfor(model: leverModel)
                collectionView?.reloadData()
                self.updatePrice()
            }else if index == 2 {
                numberTextField?.text = viewModel?.leverNumberChange(addBool: addBool)
                self.viewModel?.changePrice = true
                collectionView?.reloadData()
                self.updatePrice()
            }else if index == 5 {
                stopLossTextField?.text = viewModel?.leverLossChange(addBool: addBool)
            }else if index == 6 {
                stopProfitTextField?.text = viewModel?.leverProfitChange(addBool: addBool)
            }
            
        }
    }
}
extension LeverCollectionView: SlecterProcotol {
    func selectData(selecter:AnyObject?) {
        if SlecterManager.manager.selectPickerView?.tag == 5000 {
            leverModel.lossScales = selecter as! String
            collectionView?.reloadSections([5])
        }else {
            leverModel.profitScales = selecter as! String
            collectionView?.reloadSections([6])
        }
        
    }
}
